<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\api\controller\shop;

use app\api\controller\shop\Admin;
use think\Db;

/**
 * @title 【购物车】
 */
class Cart extends Admin {

    /**
     * @title 订单确认
     * @method post
     * @params cart_goods 
     */
    public function checkout() {




        $address_lists = db('member_address')->where('member_id', UID)->order('default desc')->select();



        //print_r($address_list);
        foreach ($address_lists as $key => $value) {


            $address_lists[$key]['address'] = $value['province'] . $value['city'] . $value['county'] . $value['detail'];
            $address_lists[$key]['default'] = ($value['default'] == 1) ? true : false;
        }

        //
        $post = input('post.');

        $cart_goods_confirm_lists = null;



        $total_price = 0;

        if (isset($post['cart_goods']) && !empty($post['cart_goods'])) {


            // $cart_goods = json_decode($cart_goods, true);
            foreach ($post['cart_goods'] as $key => $value) {


                // 从数据库里读取产品信息
                $goods = db('goods')->where('id', $value['id'])->find();

                $cart_goods_confirm_lists[$key]['id'] = $value['id'];
                $cart_goods_confirm_lists[$key]['title'] = $goods['title']; //标题
                $cart_goods_confirm_lists[$key]['quantity'] = $value['quantity']; //count
                $cart_goods_confirm_lists[$key]['image'] = $value['image']; //图片
                $cart_goods_confirm_lists[$key]['price'] = $goods['price']; //价格

                $total_price = $total_price + $goods['price'] * $value['quantity'];
            }
        }


        // 根据用户的头衔，计算折扣
        $member_group = Db::name('member_group')
                ->where('id', '=', function($query) {
                    $query->name('member')->where('id', UID)->field('group_id');
                })
                ->find();

        $member_group['discount'] = $member_group['discount'] == 0 ? 100 : $member_group['discount'];

        $total_price_final = $total_price * ($member_group['discount'] / 100);

        $discount = ($member_group['discount'] / 10);




        if ($total_price_final < 0.01) {
            $total_price_final = 0.01;
        }

        return ['code' => 0, 'msg' => 'success', 'data' => compact('address_lists', 'cart_goods_confirm_lists', 'total_price', 'total_price_final', 'discount')];
    }

}
